package bit.chapter.onelevo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChapterTransfer {
	/*
	 * 图书信息<bookId,<chapterNo, chapterId>>
	 */
	public static Map<String, Map<String, String>> bookMap = new HashMap<String, Map<String, String>>();

	/**
	 *  zhangjiexuhao(1).csv
	 *	"BOOKID","CHAPTERID","CHAPTERNO"
	 *	"371843458","371843460","0"
	 *	"371843458","371843461","1"
	 *	"371843458","371843462","2"
	 *	"385196471","385196473","0"
	 *	"385196471","385196474","1"
	 *	"385196471","385196475","2"
	 * 
	 *  章节订购18258412361.csv
	 *	"18258412361,371843458,0,000008,334123,,201,4,2016-09-12 16:21:17"
	 *	"18258412361,385196471,0,000002,439568,,201,4,2016-10-10 04:29:00"
	 *	"18258412361,404701457,0,0040000000000000000000000000000000000008,1319239,,201,1,2016-02-17 11:26:01"
	 *
	 *  解码后的用户对应的手机号,图书id,CHAPTERID,CHAPTERNO
	 *	18258412361,371843458,371843480,20
	 *	18258412361,385196471,385196495,22
	 *	18258412361,404701457,404704786,9
	 */
	public static void main(String[] args) {
		String bookInfoPath = "D:\\projects\\asiaDir\\mission\\数媒\\割接\\章节表解码\\zhangjiexuhao(1).csv";
		// 初始化章节信息到map中
		initBookMap(bookInfoPath);

		String chapterPath = "D:\\projects\\asiaDir\\mission\\数媒\\割接\\章节表解码\\章节订购18258412361.csv";
		// 转换信息
		transfer(chapterPath);
		System.out.println("over ...");
	}

	public static void initBookMap(String bookInfoPath) {
		/* 文件行 */
		String line;

		/* 图书id */
		String bookId;

		/* 章节id */
		String chapterId;

		/* 章节序号 */
		String chapterNo;

		String[] values;
		Map<String, String> tempMap;

		try (BufferedReader reader = new BufferedReader(
				new InputStreamReader(new FileInputStream(bookInfoPath), "UTF-8"));) {
			while ((line = reader.readLine()) != null) {
				/*
				 * 已逗号分隔文件行 行记录："371843458","371843460","0"
				 */
				values = line.replace("\"", "").split(",");
				bookId = values[0];
				chapterId = values[1];
				chapterNo = values[2];
				tempMap = bookMap.get(bookId);
				if (tempMap == null) {
					tempMap = new HashMap<String, String>();
					tempMap.put(chapterNo, chapterId);
					bookMap.put(bookId, tempMap);
				} else {
					if (tempMap.get(chapterNo) != null) {
						System.out.println("chapterNo重复存在");
					} else {
						tempMap.put(chapterNo, chapterId);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void transfer(String chapterPath) {
		/*
		 * 章节永久订购表数据文件行
		 */
		String line;
		/*
		 * 图书id
		 */
		String bookId;
		/*
		 * 阅读号
		 */
		String userId;
		/*
		 * 二进制订购记录，割接数据以16进制形式呈现
		 */
		String chapterlist;
		/*
		 * 当前记录存储的起始章节顺序号
		 */
		String startchpter;
		/*
		 * 二进制字符串，订购订购记录
		 */
		String bit;
		
		/*
		 * 二进制数组，订购订购记录
		 */
		int [] hexToIntArr;
		/*
		 * 章节序号
		 */
		String chapterNo;
		/*
		 * 章节id
		 */
		String chapterId;
		String[] values;
		int lineNum = 0;
		/*
		 * 字段分隔符
		 */
		char c = 0x1F;
		String splitStr = String.valueOf(c);
		Map<String, String> tempMap;
		List<Integer> chapterNoList;

		try (BufferedReader reader = new BufferedReader(
				new InputStreamReader(new FileInputStream(chapterPath), "UTF-8"));
				BufferedWriter out = new BufferedWriter(
						new OutputStreamWriter(new FileOutputStream(chapterPath + "_w1", true), "UTF-8"));) {
			while ((line = reader.readLine()) != null) {
				lineNum++;
				/* 第一行为字段名，不解析 */
				if (lineNum == 1) {
					continue;
				}
				/* "1825841236140470145700040000000000000000000000000000000000008131923920112016-02-17 11:26:01" */
				/* 确定首尾双引号，以分隔符分解行记录,判断首尾字符为双引号，再去掉 */
				if (line.startsWith("\"")) {
					line = line.substring(1, line.length());
				}
				if (line.endsWith("\"")) {
					line = line.substring(0, line.length() - 1);
				}
				values = line.split(splitStr);
				userId = values[0];
				bookId = values[1];
				startchpter = values[2];
				chapterlist = values[3];
				/* 根据图书id，获取图书章节信息 */
				tempMap = bookMap.get(bookId);
				if (tempMap == null) {
					System.out.println("图书信息不存在:" + bookId + ",line:" + line);
				} else {
					// 16进制串转二进制串数组
					hexToIntArr = hexToIntArr(chapterlist);
					chapterNoList = chapterNoIntArr(hexToIntArr,Integer.valueOf(startchpter));
					
					// 根据订购章节序号，获取章节id
					for (int i = 0; i < chapterNoList.size(); i++) {
						chapterNo = chapterNoList.get(i) + "";
						chapterId = tempMap.get(chapterNo);
						if (chapterId == null) {
							System.out.println("图书章节信息不存在:" + bookId + "——" + chapterId + ",line:" + line);
						} else {
							out.write(userId + "," + bookId + "," + chapterId + "," + chapterNo + "\n");
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

    /**
     * hex转byte数组
     * @param hex
     * @return
     */
    public static int[] hexToIntArr(String hex){
        int m = 0, n = 0;
        int byteLen = hex.length() / 2; // 每两个字符描述一个字节
        int[] result= new int[byteLen * 8];
        int intVal;
        for (int i = 0; i < byteLen; i++) {
            m = i * 2 + 1;
            n = m + 1;
            intVal = Integer.decode("0x" + hex.substring(i * 2, m) + hex.substring(m, n));

            // 通过按位&将值转为二进制格式的int数组
            for(int j = 0, v = 0;j < 8; j++){
                v = (intVal >> j & 0x01);
                result[8 * i - 1 + (8 - j)] = v;
            }
        }
        return result;
    }
	
	public static List<Integer> chapterNoIntArr(int [] intArr, int startchpter) {
		List<Integer> list = new ArrayList<Integer>();
		for(int i = 0; i < intArr.length; i++){
			if (intArr[i] == 1) {// ‘1’代表订购，
				list.add(i + startchpter);// 记录订购章节序号
			}
		}
		return list;
	}
}
